// packageA/pages/goodsList/goodsList.js
const app = getApp();
import CommonService from '../../../utils/service/commonService.js';
import Toast from '../../../miniprogram_npm/@vant/weapp/toast/toast';
import Dialog from '../../../miniprogram_npm/@vant/weapp/dialog/dialog';

Page({
  /**
   * 页面的初始数据
   */
  data: {
    //列表
    list:[],
    //已选列表
    listMap: {},
    listSelect: [],
    //页码
    page: 1,
    //是否无更多
    notMore: true,
    //无数据
    showNothing:false,
    //搜索词
    searchValue:'',
    //选择框
    showSelect:false,
    //选择数据
    selectList:[],
    //当前选择
    selectField:'',
    //选择框标题
    selectTitle:'',
    //显示选择搜索框
    showSelectSearch:false,
    //选择框搜索
    valueSearch: '',
    //物资品类
    classifyId: null,
    classifyName: '物资品类',
    //传参
    paramObj: null,
    //是否是可选择状态
    showCheck: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      //在这里给map赋值，避免后面操作时set方法不可用
      listMap: new Map()
    })

    if(options.paramObj){
      this.setData({
        showCheck: true
      })

      let paramObj=JSON.parse(options.paramObj);
      console.log('物资列表传参');
      console.log(paramObj);

      this.setData({
        paramObj: paramObj
      })

      //选中状态
      if(paramObj.ids.length){
        let map=new Map();
        paramObj.ids.forEach(item => {
          map.set(item,item);
        });
        this.setData({
          listMap: map
        })
      }  
    }

    //获取列表数据
    this.getList();
  },

  //获取列表数据
  getList(){
    Toast.loading({
      duration: 0,
      forbidClick: true,
      message: '加载中...'
    });

    let user=app.globalData.userInfo;

    let dataObj={
      selectFields: ['id','name','pic','factory','spec','params','classify','unit','code','price'],
      'subsidiaryOrgan.id': user.departObj[0].companyId,
      sort: {
        id: -1
      },
      page: {
        page: this.data.page,
        pageSize: 10
      }
    }  

    //模糊查询
    if(this.data.searchValue){
      dataObj.name='%' +this.data.searchValue+ '%';
    }

    //品类
    if(this.data.classifyId){
      dataObj['classify.id']=this.data.classifyId;
    }
    
    let param = {
      isAuth: false,
      className: 'clientProducts',
      data: dataObj
    }

    CommonService.goFindList(param).then(res => {
      if(res.data.data && res.data.data.result && res.data.data.result.length) {
        let result=res.data.data.result;
        console.log('商品列表');
        console.log(result);

        //选中状态
        let listMap=this.data.listMap;        
        if(listMap.size){
          let arr=[];
          result.forEach(item => {
            if(listMap.get(item.id)){
              item.checked=true;
              listMap.set(item.id,item);
              arr.push(item);
            }
          });        
          this.setData({
            listMap: listMap,
            listSelect: arr
          })
        }
      
        this.setData({
          list: this.data.list.concat(result)
        })
        Toast.clear();
      }else{
        this.setData({
          notMore: false
        })
        if(this.data.page==1){
          this.setData({
            showNothing: true
          })
          Toast.clear();
        }else{
          Toast.fail('没有更多了');
        }
      }
    }).catch((error) => {
      this.setData({
        showNothing: true
      })
      Toast.clear();
    })
  },

  //刷新列表和页码
  refreshListAndPage(){
    this.setData({
      list: [],
      page:1,
      notMore: true,
      showNothing: false
    })
    this.getList();
  },

  //获取搜索词
  onChangeSearch(e) {
    this.setData({
      searchValue: e.detail.value
    })
  },

  //点击搜索
  onSearch(){
    this.refreshListAndPage();
  },

  //显示选择框
  onShowSelect(e){
    this.setData({
      selectList: []
    })

    let dataset=e.currentTarget.dataset;
    let field=dataset.field;

    this.setData({
      showSelect: true,
      selectField: field
    })

    //物资品类
    if(field=='classify'){
      this.setData({
        selectTitle: '物资品类',
        showSelectSearch: true
      })
      this.getClassifyList();
    }
  },

  //隐藏选择框
  onCloseSelect(){
    this.setData({
      showSelect: false,
      valueSearch: '',
      disabled: false
    })
  },

  //确认选项
  onConfirmSelect(e){
    let selectField=this.data.selectField;
    let id=null,name=null,obj=null;

    //物资品类
    if(selectField=='classify'){
      id='classifyId';
      name='classifyName';
    }  

    if(id && name){
      this.setData({
        [id]:e.detail.value.id,
        [name]:e.detail.value.text
      })
    }

    if(obj){
      this.setData({
        [obj]:e.detail.value.obj
      })
    }

    //物资品类
    if(selectField=='classify'){
      //获取列表数据
      this.refreshListAndPage();
    }  

    this.onCloseSelect();
  },

  //清除选项
  onCancelSelect(){
    let selectField=this.data.selectField;
    let id=null,name=null,obj=null;

    //物资品类
    if(selectField=='classify'){
      id='classifyId';
      name='classifyName';
    }

    if(id && name){
      this.setData({
        [id]: null,
        [name]: '物资品类'
      })
    }

    if(obj){
      this.setData({
        [obj]:null
      })
    }

    //物资品类
    if(selectField=='classify'){
      //获取列表数据
      this.refreshListAndPage();
    }

    this.onCloseSelect();
  },

  //选择框搜索
  onChangeSelectVal(e){
    let selectField=this.data.selectField;

    this.setData({
      valueSearch: e.detail
    })

    //物资品类
    if(selectField=='classify'){
      this.getClassifyList();
    }
  },

  //查询物资品类
  getClassifyList(){
    let user=app.globalData.userInfo;
    let param = {
      isAuth: false,
      className: 'clientClassify',
      data: {
        searchAll: true,
        selectFields: ['id','name','subsidiaryOrgan'],
        'subsidiaryOrgan.id': user.departObj[0].companyId
      }
    }

    if(this.data.valueSearch){
      param.data.name='%' + this.data.valueSearch + '%';
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text: item.name,
            id: item.id
          });
        });

        this.setData({
          selectList: arr
        })
      }
    }).catch((error) => {
    })
  },


  //选择列表
  onChangeCheck({currentTarget}) {
    if(this.data.showCheck){
      let detail=currentTarget.dataset.detail;
      let list=this.data.list;
      let listMap=this.data.listMap;
  
      list.forEach(item => {
        if(item.id==detail.id){
          //点击复选框时切换选中
          item.checked=!item.checked;
          if(item.checked){
            //选中的放入已选列表，利用map避免重复
            listMap.set(item.id,item);
          }else{
            //未选中的从map中删除
            listMap.delete(item.id);
          }
        }
      });
  
      //名字存入数组
      let arr=[];
      listMap.forEach(function(value) {
        arr.push(value);
      })
  
      this.setData({
        list: list,
        listMap: listMap,
        listSelect: arr
      })
    }
  },

  //确认选择
  onConfirmCheck(){
    //商品id
    let listSelect=this.data.listSelect;
    let ids=[]; 
    listSelect.forEach(item => {
      ids.push(item.id);
    });

    let pages = getCurrentPages();
    let prevPage = pages[pages.length - 2];

    prevPage.getProduct(ids);
    wx.navigateBack();
  },

  //跳转添加/编辑
  goToAdd({currentTarget}){
    let obj={}

    if(currentTarget.dataset.detail){
      let detail=currentTarget.dataset.detail;
      obj.id=detail.id;
    }

    wx.navigateTo({
      url: "/packageA/pages/goodsAdd/goodsAdd?paramObj="+JSON.stringify(obj)
    })
  },

  //跳转详情
  goToDetail({currentTarget}){
    let detail=currentTarget.dataset.detail;

    let obj={
      id: detail.id
    }

    wx.navigateTo({
      url: "/packageA/pages/goodsDetail/goodsDetail?paramObj="+JSON.stringify(obj)
    })
  },

  //删除
  onDelete(e){
    Dialog.confirm({
      title: '确定删除此物资商品吗',
      confirmButtonText:'确定',
      cancelButtonText:'不删除了'
    }).then(() => {
      let detail=e.currentTarget.dataset.detail;

      let param={
        className:"clientProducts",
        data:{
          id:detail.id
        }
      }

      CommonService.goDelete(param).then(res=>{
        if (res.statusCode == 200 && res.data.success == true){
          Toast.success('已删除');
          setTimeout(() => {
            //刷新列表和页码
            this.refreshListAndPage();
          }, 1000);
        }else{
          Toast.fail('操作失败');
        }
      }).catch((error) => {
        Toast.fail('操作失败');
      })

    }).catch(() => {
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if(this.data.notMore){
      this.setData({
        page: this.data.page + 1
      })
      this.getList();
    }
  }
})